package com.straw.hat.springboot.test.util;

import com.ql.util.express.ExpressRunner;
import com.ql.util.express.IExpressContext;
import com.straw.hat.springboot.test.script.context.QLExpressContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

/**
 * @author jianshan@byai.com
 * @date 2021/3/9 3:14 PM
 * describe:
 */
public class QleExpressUtil implements ApplicationContextAware {

    private static ExpressRunner runner;


    private static boolean isInitialRunner = false;

    static {
        runner = new ExpressRunner();
    }

    private ApplicationContext applicationContext;// spring上下文



    @SuppressWarnings("unchecked")
    public Object execute(String statement, Map<String, Object> context)
            throws Exception {
        initRunner(runner);
        IExpressContext expressContext = new QLExpressContext(context, applicationContext);
        return runner.execute(statement, expressContext, null, true, false);
    }

    private void initRunner(ExpressRunner runner) {
        if (isInitialRunner) {
            return;
        }
        synchronized (runner) {
            if (isInitialRunner) {
                return;
            }
            try {
                runner.addFunctionOfServiceMethod("读取用户信息",applicationContext.getBean("bizLogicBean"), "getUserInfo", new Class[] {String.class}, null);
                runner.addMacro("判定用户是否vip","userDO.salary>200000");
            } catch (Exception e) {
                throw new RuntimeException("初始化失败表达式", e);
            }
        }
        isInitialRunner = true;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
